
import { isContainsVal } from '@/utils/index'

export function flatMenu(flatData, { exclude = [], schema = { id: 'menuId', parentId: 'menuParent' }}) {
  const result = []
  const map = {}
  flatData.forEach(item => {
    const menuItem = {}
    menuItem.menuId = item.menuId
    menuItem.menuParent = item.menuParent
    // alwaysShow: true, will always show the root menu
    if (item.menuType === '1') {
      menuItem.path = item.routePath
      menuItem.component = 'Layout'
      menuItem.hidden = item.hiddenFlg !== '0'
      menuItem.redirect = item.redirectPath
      menuItem.alwaysShow = item.alwaysShowFlg === '1'
      menuItem.name = item.routeName
      menuItem.meta = {
        title: item.routeName,
        icon: item.iconName,
        noCache: item.nocacheFlg === '1',
        link: item.link
      }
      menuItem.children = []
    }

    if (item.menuType === '2') {
      menuItem.path = item.routePath
      menuItem.component = item.routeView
      menuItem.name = item.routeName
      menuItem.meta = {
        title: item.routeName,
        icon: item.iconName,
        noCache: item.nocacheFlg === '1',
        link: item.link
      }
    }

    map[item[schema.id]] = menuItem
  })

  // 根据parentId将子节点添加到父节点的children属性下
  flatData.forEach(item => {
    if (isContainsVal(item[schema.parentId])) {
      map[item[schema.parentId]].children.push(map[item[schema.id]])
    } else {
      result.push(map[item[schema.id]])
    }
  })

  function traverse(childArr) {
    const newChildArr = childArr.filter((node) => {
      return !exclude.some(id => id === node[schema.id])
    })
    newChildArr.forEach((item) => {
      item.children = traverse(item.children)
    })
    return newChildArr
  }
  if (Array.isArray(exclude) && exclude.length > 0 && isContainsVal(exclude[0])) {
    // eslint-disable-next-line no-const-assign
    result = traverse(result)
  }
  return result
}
